//
//  OAuthViewController.swift
//  我的微博
//
//  Created by teacher on 15/7/29.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    // 创建一个 webView
    var  webView : UIWebView?
    
    override  func  loadView() {
        webView = UIWebView()
        
        view = webView
        
        webView?.delegate  = self
        
        webView?.loadRequest(NSURLRequest(URL:NetWorkTools.shardNetWorkTool.getAuthorize()))
        
        
    }
   
    func webViewDidStartLoad(webView: UIWebView) {
        print(__FUNCTION__)
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        print(__FUNCTION__)
        
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 获取 request 中的url 后面部分   就是 去除  baseUrl 后的部分
        let  urlString = request.URL!.absoluteString
        print("---\(request)")
        print("----\(urlString)")
        if !urlString .hasPrefix(NetWorkTools.shardNetWorkTool.redirectUri) {
           
            return true
        }
        if let query = request.URL?.query where query.hasPrefix("code=")  {
        
            // 获得  code
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            // 获得  token
//            NetWorkTools.shardNetWorkTool.login
            NetWorkTools.shardNetWorkTool.loginToken(code, finished: { (result, error) -> () in
                print(result)
                UserAccount(dictData: result! )
            })
            
            
            
        }
        
        return false
    }
    
}
